<template>
  <div id="wrap">
    <h1>effectScope案例3</h1>
    <button @click="createTimer">添加定时器</button>
    <div v-for="(item, index) in times" :key="index">
      <button>定时器{{ index + 1 }}:{{ item.time }}</button>
      <button type="button" @click="removeTimer(index)">清除定时器</button>
      <hr />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, type Ref, EffectScope, effectScope, onScopeDispose } from 'vue';

interface ClassB {
  time: Ref<number>;
  scope: EffectScope;
}

//创建一个计时器的组合函数
function userTimer(): ClassB {
  const time = ref(0);
  let interval: ReturnType<typeof setInterval>;
  //使用effectScope创建作用域
  const scope = effectScope();
  scope.run(() => {
    //开启定时器
    interval = setInterval(() => {
      time.value++;
    }, 1000);
    //在作用域销毁时清理定时器
    onScopeDispose(() => {
      clearInterval(interval);
      console.log('作用销毁，提前清除数据资源');
    });
  });
  return { time, scope }; // { time:Ref<number> , scope:EffectScope }
}

//管理多个定时器
type TimesRef = Ref<ClassB[]>; // 类型封装 处理方法2
const times: TimesRef = ref([]); //处理方法2
//创建一个函数 创建定时器
function createTimer() {
  const newTimer: ClassB = userTimer();
  times.value.push(newTimer); //处理方法2
}
//移除计时器并清理作用域
function removeTimer(index: number) {
  const timerToRemove = times.value[index];
  if (timerToRemove) {
    timerToRemove.scope.stop(); //停止该作用域并触发资源清理
  }
  times.value.splice(index, 1);
}
</script>
